import React from 'react'
import Input from '../input'
import DatePicker from 'react-date-picker'
import 'react-date-picker/index.css'
import '../../ui/date-picker.css'
import style from './style'
import { findDOMNode } from 'react-dom'
import { error } from '../'
import util from '../../util'
import {FieldContainer, FieldBox} from '../form'


export default
class extends React.Component {

  static propsType = {
    onChange: React.PropTypes.func.required,
    label: React.PropTypes.string,
    time: React.PropTypes.string
  }

  state = {
    edit: false,
    time: ''
  }

  constructor(props) {
    super(props)
    this.state = {
      edit: false,
      time: props.time || ''
    }
  }

  componentWillReceiveProps(props) {
    if (props.time != this.props.time) {
      this.setState({
        time: props.time
      })
    }
  }

  handleClick = e => {
    this.setState({
      edit: false
    })
    util.unbind(document, 'click', this.handleClick)
  }

  handlePickerClick(e) {
    e.stopPropagation()
    e.nativeEvent.stopImmediatePropagation()
  }

  handleInputClick(e) {
    e.stopPropagation()
    e.nativeEvent.stopImmediatePropagation()
    this.setState({
      edit: true
    })
    util.bind(document, 'click', this.handleClick)
  }

  handlePickerChange(time, m) {

    this.props.onChange(m.timestamp)

    setTimeout(() => {
      this.setState({
        edit: false
      })
    }, 150)
  }

  handleChange(e) {
    const time = e.target.value
    const val = new Date(time)
    if (val != 'Invalid Date') {
      this.props.onChange(val)
    } else {
      this.props.onChange('')
    }
    this.setState({
      time
    })
  }

  render() {
    const {
      disabled,
      label, name, required, className, bubbleList, labelWidth, width,placeholder, ...other
    } = this.props;
    return (
      <FieldBox
        label={label}
        name={name}
        required={required}
        labelWidth={labelWidth}
      >
        <div className={style.root}
         >
          <Input 
            ref="input"
            required={this.props.required}
            label={''}
            value={this.state.time}
            onClick={::this.handleInputClick}
            onChange={::this.handleChange}
            className={style.input}
            bubbleList={bubbleList}
            name={name}
            disabled={disabled}
            placeholder={placeholder}
            width={width}
          />

          {
            this.state.edit?
            <DatePicker 
              onClick={::this.handlePickerClick}
              onChange={::this.handlePickerChange}
              className={style.picker}
              weekNumbers={false}
              data-role={'datePicker'}
              locale="zh-cn"
              hideFooter
            />: null
          } 
        </div>
      </FieldBox>
    )
  }
}
